import Vue from 'vue'
import Vuex from 'vuex'
import { saveToLocal, getFromLocal } from '../utils/storage'
Vue.use(Vuex)
/*
* persistence 是否持久化 localStorage
* */
const initData = {
  userInfo: { // 用户信息
    persistence: true,
    default: ''
  }
}

const state = {
}
const mutations = {
}

for (const key in initData) {
  const upcaseKey = key.toUpperCase()
  if (initData[key].persistence) {
    // Todo 处理初始化 string -> json 解析
    state[key] = getFromLocal('localStorage', 'bizdesk', key, initData[key].default)
    // Todo  mutations 添加 设置state 方法
    mutations[upcaseKey] = (storeState, obj) => {
      // 设置 localStorage
      saveToLocal('localStorage', 'bizdesk', key, obj)
      saveToLocal('localStorage', 'bizdesk', key, obj)
      storeState[key] = obj
    }
  } else {
    state[key] = initData[key].default
    state[key] = getFromLocal('sessionStorage', 'bizdesk', key, initData[key].default)
    mutations[upcaseKey] = (storeState, obj) => {
      storeState[key] = obj
    }
  }
}

const store = new Vuex.Store({
  state,
  mutations
})

export default store
